<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { delTable, genBatchGenCode, getGenList, previewTable, synchDb } from '@/api/code/gen/index'
import { downloadBlobFile } from '@/utils'
import { checkPermission } from '@/utils/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
// import CreateDialog from './components/CreateDialog.vue'
import ImportDialog from './components/importDialog.vue'
import PreviewDialog from './components/PreviewDialog.vue'
import type { GenList, GenQueryParams } from '@/api/code/gen/type'
import { debounce } from 'es-toolkit'

const router = useRouter()

// form
const formValue = ref<GenQueryParams & { daterange?: string[] }>({
	tableName: '',
	tableComment: '',
	daterange: []
})
const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '表名称',
		prop: 'tableName'
	},
	{
		type: 'input',
		label: '表描述',
		prop: 'tableComment'
	},
	{
		type: 'date-picker',
		label: '创建时间',
		prop: 'daterange',
		attrs: {
			type: 'daterange',
			startPlaceholder: '开始时间',
			endPlaceholder: '结束时间',
			valueFormat: 'YYYY-MM-DD HH:mm:ss'
		}
	}
])

const previewDialogShow = ref(false)
// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<GenList[]>([])
const selectionList = ref<any[]>([])

const columns = ref<TableColums[]>([
	{
		type: 'selection',
		width: 55,
		align: 'center'
	},
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '表名称',
		prop: 'tableName'
	},
	{
		label: '表描述',
		prop: 'tableComment'
	},
	{
		label: '实体',
		prop: 'className'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		sortable: 'custom'
	},
	{
		label: '更新时间',
		prop: 'updateTime'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 280,
		align: 'center'
	}
])

// dialog
// const createDialogRef = useTemplateRef('createDialogRef')
const importDialogRef = useTemplateRef('importDialogRef')
const previewInfo = ref<any>({})

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		}

		// 处理时间范围
		if (formValue.value.daterange && formValue.value.daterange.length === 2) {
			params['params[beginTime]'] = formValue.value.daterange[0]
			params['params[endTime]'] = formValue.value.daterange[1]
			delete params.daterange
		}

		const res = await getGenList(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

const handleSelectionChange = (val: GenList[]) => {
	selectionList.value = val
}

// const handelAdd = () => {
// 	createDialogRef.value?.setVisible(true)
// }

const handelImport = () => {
	importDialogRef.value?.init()
}

const handelEdit = (row: GenList) => {
	// 跳转到编辑页面
	router.push({
		path: `/tool/gen-edit/index/${row.tableId}`,
		query: { pageNum: 1 }
	})
}

const handelPreview = async (row: GenList) => {
	previewDialogShow.value = true
	const { data } = await previewTable(row.tableId)
	previewInfo.value = data
}

const handelSync = async (row: GenList) => {
	await ElMessageBox.confirm(`确认要强制同步"${row.tableName}"表结构吗？`, {
		title: '系统提示',
		type: 'warning',
		confirmButtonText: '确定',
		cancelButtonText: '取消'
	})
	await synchDb(row.tableName)
	ElMessage.success('同步成功')
	getTableData()
}

const handelGenCode = debounce((tableNames: string) => genCodeFn(tableNames), 800, {
	edges: ['leading']
})

const genCodeFn = (tableNames: string) => {
	genBatchGenCode({ tables: tableNames }).then(res => {
		downloadBlobFile(res.data.data, res.data.filename || new Date().getTime() + '.zip')
	})
}

const handelDelete = async (row: GenList) => {
	await ElMessageBox.confirm(`是否确认删除表编号为"${row.tableId}"的数据项？`, {
		title: '系统提示',
		type: 'warning',
		confirmButtonText: '确定',
		cancelButtonText: '取消'
	})
	await delTable(row.tableId)
	ElMessage.success('删除成功')
	getTableData()
}

const handelBatchGenCode = () => {
	if (selectionList.value.length === 0) {
		ElMessage.warning('请选择要生成的表')
		return
	}
	const tableNames = selectionList.value.map(v => v.tableName).join(',')

	handelGenCode(tableNames)
}

const handelBatchDelete = async () => {
	if (selectionList.value.length === 0) {
		ElMessage.warning('请选择要删除的表')
		return
	}
	const tableIds = selectionList.value.map(v => v.tableId).join(',')
	await ElMessageBox.confirm(`是否确认删除选中的${selectionList.value.length}个数据项？`, {
		title: '系统提示',
		type: 'warning',
		confirmButtonText: '确定',
		cancelButtonText: '取消'
	})
	await delTable(tableIds)
	ElMessage.success('删除成功')
	getTableData()
}

onMounted(() => {
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
				@selectionChange="handleSelectionChange"
			>
				<template #headerLeft>
					<el-button
						:disabled="!checkPermission(['tool:gen:import'])"
						@click="handelImport"
					>
						导入
					</el-button>
					<el-button
						type="primary"
						:disabled="!checkPermission(['tool:gen:code']) || selectionList.length === 0"
						@click="handelBatchGenCode"
					>
						生成
					</el-button>
					<!-- <el-button
						type="primary"
						:disabled="!checkPermission(['admin'])"
						@click="handelAdd"
					>
						创建
					</el-button> -->

					<el-button
						type="danger"
						:disabled="!checkPermission(['tool:gen:remove']) || selectionList.length === 0"
						@click="handelBatchDelete"
					>
						删除
					</el-button>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['tool:gen:preview'])"
						type="primary"
						link
						@click="handelPreview(row)"
					>
						预览
					</el-button>
					<el-button
						v-if="checkPermission(['tool:gen:edit'])"
						type="primary"
						link
						@click="handelEdit(row)"
					>
						修改
					</el-button>

					<el-button
						v-if="checkPermission(['tool:gen:edit'])"
						type="primary"
						link
						@click="handelSync(row)"
					>
						同步
					</el-button>
					<el-button
						v-if="checkPermission(['tool:gen:code'])"
						type="primary"
						link
						@click="handelGenCode(row.tableName)"
					>
						生成代码
					</el-button>
					<el-button
						v-if="checkPermission(['tool:gen:remove'])"
						type="danger"
						link
						@click="handelDelete(row)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<!-- <CreateDialog
			ref="createDialogRef"
			@refresh="getTableData"
		/> -->
		<ImportDialog
			ref="importDialogRef"
			@refresh="getTableData"
		/>
		<!-- 查看弹窗 -->
		<PreviewDialog
			v-model:show="previewDialogShow"
			:preview-info="previewInfo"
		/>
	</div>
</template>
